//
//  LHMenuViewController.m
//  EPA
//
//  Created by 卢浩 on 16/4/15.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHMenuViewController.h"
#import "LHAVPlayerManager.h"
#import "LHRadioDetailViewController.h"
#import "LHUserInfoManager.h"
#import "LHReadCollectController.h"
#import "LHLoginViewController.h"

// 抽屉展开的程度
#define kMenuLeftWidth [UIScreen mainScreen].bounds.size.width * 0.7

@interface LHMenuViewController ()<UITableViewDataSource, UITableViewDelegate>

// 默认左侧tableView
@property (nonatomic,strong) UITableView *leftTableView;

//手势
@property (nonatomic,strong) UIPanGestureRecognizer *pan;


//底部音乐视图
@property (nonatomic,strong) UILabel *musicTitleLable;

@property (nonatomic,strong) UILabel *musicDescLable;

@property (nonatomic,strong) UIImageView *musicImgView;

@property (nonatomic,strong) UIButton *musicPlayBtn;

@property (nonatomic,strong) UIButton *musicNextBtn;

@property (nonatomic,strong) UIButton *musicLastBtn;

//用户信息视图

@property (nonatomic,strong) UIImageView *iconImgView;

@property (nonatomic,strong) UIButton *nameBtn;

@property (nonatomic,strong) UIButton *collectBtn;

@end

@implementation LHMenuViewController
// 判断当前是否展开
- (BOOL)isShowing {
    if (self.centerViewController.view.transform.tx > 0) {
        return YES;
    }
    return NO;
}
// 初始化方法
static LHMenuViewController *CK_menuVC = nil;
+ (instancetype)instanceWithLeftViewController:(UIViewController *)leftVC CenterViewController:(UIViewController *)centerVC {
    @synchronized(self) {
        if (!CK_menuVC) {
            
            CK_menuVC = [[LHMenuViewController alloc]init];
            // 设置window的rootViewController
            [UIApplication sharedApplication].keyWindow.rootViewController = CK_menuVC;
            // 设置属性
            CK_menuVC.leftViewController = leftVC;
            CK_menuVC.centerViewController = centerVC;
            // 添加子视图控制器和子视图
            if (leftVC) {
                [CK_menuVC addChildViewController:leftVC];
                [CK_menuVC.view addSubview:leftVC.view];
            }else {
                [CK_menuVC setupLeftViewController];
            }
            if (centerVC) {
                [CK_menuVC addChildViewController:centerVC];
                [CK_menuVC.view addSubview:centerVC.view];
            }
        }
    }
    return CK_menuVC;
}
// 默认的菜单视图
- (void)setupLeftViewController {
    self.leftTableView = [[UITableView alloc]    initWithFrame:CGRectMake(-kMenuLeftWidth, 0, kMenuLeftWidth, self.view.frame.size.height) style:UITableViewStylePlain];
    
//    self.leftTableView.bounces = NO;
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.backgroundColor = [UIColor darkGrayColor];
    self.leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 设置数据源
    self.leftTableView.dataSource = self;
    // 代理
    self.leftTableView.delegate = self;
    [self.view addSubview:self.leftTableView];
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

// 数据源代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 3) {
        return self.menuArray.count;;
    }else{
        return 0;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuserID = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuserID];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuserID];
    }
    
    //设置Cell背景色
    UIView *backgrdView = [[UIView alloc] initWithFrame:cell.frame];
    backgrdView.backgroundColor = [UIColor darkGrayColor];
    cell.backgroundView = backgrdView;
    
    //设置文字显示样式
    cell.textLabel.text = self.menuArray[indexPath.row];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.shadowColor = [UIColor lightGrayColor];

    return cell;
}
// menuArray的setter方法
- (void)setMenuArray:(NSMutableArray *)menuArray {
    if (_menuArray != menuArray) {
        _menuArray  = nil;
        _menuArray  = menuArray;
        [self.leftTableView reloadData];
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // 取消选中状态
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 代理 传值
    if ([self.menuDelegate respondsToSelector:@selector(didClickMenuIndex:Title:)]) {
        [self.menuDelegate didClickMenuIndex:indexPath.row Title:self.menuArray[indexPath.row]];
    }
    // 关闭抽屉
    [self hideLeftViewController];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 64;
    }else if(section == 1) {
        return 122;
    }else if(section == 3){
        return 2;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [self creatSection0View];
        return view;
    }else if(section == 1) {
        UIView *view = [self creatSection1View];
        return view;
    }else{
        UIView *view = [[UIView alloc]init];
        UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kMenuLeftWidth, 2)];
        imgView.backgroundColor = [UIColor lightGrayColor];
        [view addSubview:imgView];
        return view;
    }
}

- (UIView *)creatSection0View{
    CGFloat num1 = (kMenuLeftWidth - 30 * 4) / 5;
    
    UIView *view = [[UIView alloc]init];
    
    UIButton *searchBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    searchBtn.frame = CGRectMake(num1, 27, 30, 30);
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"搜索"] forState:(UIControlStateNormal)];
    [view addSubview:searchBtn];
    
    UIButton *downloadBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    downloadBtn.frame = CGRectMake(searchBtn.frame.origin.x + 30 + num1, 27, 30, 30);
    [downloadBtn setBackgroundImage:[UIImage imageNamed:@"下载"] forState:(UIControlStateNormal)];
    [view addSubview:downloadBtn];
    
    UIButton * houseBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    houseBtn.frame = CGRectMake(downloadBtn.frame.origin.x + 30 + num1, 27, 30, 30);
    [houseBtn setBackgroundImage:[UIImage imageNamed:@"收藏"] forState:(UIControlStateNormal)];
    [view addSubview:houseBtn];
    
    UIButton *infoBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    infoBtn.frame = CGRectMake(houseBtn.frame.origin.x + 30 + num1, 27, 30, 30);
    [infoBtn setBackgroundImage:[UIImage imageNamed:@"信息"] forState:(UIControlStateNormal)];
    [view addSubview:infoBtn];
    
    return view;
}

- (UIView *)creatSection1View{
    UIView *view = [[UIView alloc]init];
    
    UIImageView *iconImgView = [[UIImageView alloc]initWithFrame:CGRectMake(kMenuLeftWidth/2 - 110, 11, 100, 100)];
    iconImgView.image = [UIImage imageNamed:@"icon"];
    iconImgView.layer.cornerRadius = 50;
    iconImgView.layer.masksToBounds = YES;
    self.iconImgView = iconImgView;
    [view addSubview:self.iconImgView];
    
    UIButton *nameButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    nameButton.frame = CGRectMake(kMenuLeftWidth/2, 11, kMenuLeftWidth/2 - 10, 40);
    nameButton.layer.cornerRadius = 5;
    nameButton.layer.masksToBounds = YES;
    nameButton.layer.borderWidth = 1;
    nameButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [nameButton setTitle:@"未登录" forState:(UIControlStateNormal)];
    [nameButton setTintColor:[UIColor whiteColor]];
    [nameButton addTarget:self action:@selector(nameBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    self.nameBtn = nameButton;
    [view addSubview:self.nameBtn];
    
    UIButton *collectBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    collectBtn.frame = CGRectMake(kMenuLeftWidth/2, 70, kMenuLeftWidth/2 - 10, 40);
    collectBtn.layer.cornerRadius = 5;
    collectBtn.layer.masksToBounds = YES;
    collectBtn.layer.borderWidth = 1;
    collectBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    [collectBtn setTitle:@"收藏(未登录)" forState:(UIControlStateNormal)];
    [collectBtn addTarget:self action:@selector(collectBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    [collectBtn setTintColor:[UIColor whiteColor]];
    self.collectBtn = collectBtn;
    [view addSubview:self.collectBtn];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if(section == 2){
        return 115;
    }else if(section == 0){
        return 2;
    }else if(section == 1){
        return 2;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    if (section == 2) {
        view.backgroundColor = [UIColor darkGrayColor];
        
        UIImageView *iconImg = [[UIImageView alloc]init];
        iconImg.frame = CGRectMake(20, 5, 50, 50);
        iconImg.image = [UIImage imageNamed:@"icon"];
        iconImg.layer.cornerRadius = 25;
        iconImg.layer.masksToBounds = YES;
        self.musicImgView = iconImg;
        [view addSubview:self.musicImgView];
        
        UIButton *playBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        playBtn.frame = CGRectMake(kMenuLeftWidth - 20 - 50, 5, 50, 50);
        [playBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:(UIControlStateNormal)];
        playBtn.userInteractionEnabled = NO;
        playBtn.layer.masksToBounds = YES;
        self.musicPlayBtn = playBtn;
        [view addSubview:self.musicPlayBtn];
        
        UIButton *nextBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        nextBtn.frame = CGRectMake(kMenuLeftWidth - 20 - 50, 60, 50, 50);
        [nextBtn setBackgroundImage:[UIImage imageNamed:@"M下一曲"] forState:(UIControlStateNormal)];
        nextBtn.userInteractionEnabled = NO;
        nextBtn.layer.masksToBounds = YES;
        self.musicNextBtn = nextBtn;
        [view addSubview:self.musicNextBtn];
        
        UIButton *lastBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        lastBtn.frame = CGRectMake(kMenuLeftWidth - 20 - 120, 60, 50, 50);
        [lastBtn setBackgroundImage:[UIImage imageNamed:@"M上一曲"] forState:(UIControlStateNormal)];
        lastBtn.userInteractionEnabled = NO;
        lastBtn.layer.masksToBounds = YES;
        self.musicLastBtn = lastBtn;
        [view addSubview:self.musicLastBtn];
        
        UILabel *lable1 = [[UILabel alloc]initWithFrame:CGRectMake(iconImg.frame.origin.x + iconImg.frame.size.width + 15, 5, kMenuLeftWidth - playBtn.frame.size.width - iconImg.frame.size.width - 40 - 30, 50)];
        lable1.textColor = [UIColor lightGrayColor];
        lable1.text = @"暂无电台播放";
        lable1.numberOfLines = 0;
        self.musicTitleLable = lable1;
        UILabel *lable2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 60, lable1.frame.size.width, 50)];
        lable2.textColor = [UIColor lightGrayColor];
        lable2.text = @"暂无电台播放";
        lable2.numberOfLines = 0;
        self.musicDescLable = lable2;
        [view addSubview:self.musicTitleLable];
        [view addSubview:self.musicDescLable];
        
        return view;
    }
    if (section == 3) {
        return view;
    }
    view.backgroundColor = [UIColor lightGrayColor];
    return view;
}

// 获取抽屉方法
+ (instancetype)getMenuViewController {
    return CK_menuVC;
}

// 展示左侧菜单
- (void)showLeftViewController {
    // 动画展开
    [self showLeftViewController:0.7];
}
- (void)showLeftViewController:(CGFloat)duration{
    self.centerViewController.view.userInteractionEnabled = NO;
    
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        if (!self.leftTableView) {
            [self.view insertSubview:self.leftViewController.view belowSubview:self.centerViewController.view];
            self.leftViewController.view.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        }else{
            [self.view insertSubview:self.self.leftTableView belowSubview:self.centerViewController.view];
            self.leftTableView.transform = CGAffineTransformMakeTranslation(kMenuLeftWidth, 0);
        }
    }];

}
// 关闭左侧菜单
- (void)hideLeftViewController {
    [self hideLeftViewController:0.7];
}
- (void)hideLeftViewController:(CGFloat)duration {
    self.centerViewController.view.userInteractionEnabled = YES;
    
    // 动画关闭
    [UIView animateWithDuration:duration animations:^{
        self.centerViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        if (!self.leftTableView) {
            self.leftViewController.view.transform = CGAffineTransformMakeTranslation(0, 0);
        }else{
            self.leftTableView.transform = CGAffineTransformMakeTranslation(0, 0);
        }
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 手势
    self.pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithPanGesture:)];
    
}

- (void)addPanGesture{
    [self.view addGestureRecognizer:self.pan];
}

- (void)removePanGesture{
    [self.view removeGestureRecognizer:self.pan];
}

// 静态变量保存初始状态
static CGPoint begin;
static CGAffineTransform transform;
- (void)panMenuWithPanGesture:(UIPanGestureRecognizer *)pan {
    // 位移量
    CGPoint translatePoint = CGPointZero;
    // 开始手势时的位置
    if (pan.state == UIGestureRecognizerStateBegan) {
        begin = [pan locationInView:self.view];
        transform = self.centerViewController.view.transform;
    }
    // 手势过程中的位置
    if (pan.state == UIGestureRecognizerStateChanged) {
        CGPoint end = [pan locationInView:self.view];
        translatePoint = CGPointMake(end.x - begin.x, 0);
    }
    // 手势结束时的位置
    if (pan.state == UIGestureRecognizerStateCancelled || pan.state == UIGestureRecognizerStateEnded) {
        if ([pan velocityInView:self.view].x > 0) {
            // 动画设置动画时长
            [self showLeftViewController:0.13];
        }else {
            [self hideLeftViewController:0.13];
        }
        return;
    }
    // 手势过程中，对视图进行位移
    if(self.centerViewController.view.transform.tx >= 0 && self.centerViewController.view.transform.tx <= kMenuLeftWidth) {
        self.centerViewController.view.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        if (!self.leftTableView) {
            self.leftViewController.view.transform = CGAffineTransformTranslate(transform,translatePoint.x, 0);
        }else{
            self.leftTableView.transform = CGAffineTransformTranslate(transform, translatePoint.x, 0);
        }
    }
}

//设置音乐视图
- (void)setMusicViewWithTitle:(NSString *)title Desc:(NSString *)desc Img:(NSString *)imgStr{
    self.musicTitleLable.text = title;
    self.musicDescLable.text = desc;
    [self.musicImgView sd_setImageWithURL:[NSURL URLWithString:imgStr]];
    //设置Playbtn图片
    self.musicPlayBtn.userInteractionEnabled = YES;
    if ([LHAVPlayerManager shareInstant].avPlayer.rate == 0) {
        [self.musicPlayBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:(UIControlStateNormal)];
    }else if ([LHAVPlayerManager shareInstant].avPlayer.rate == 1){
        [self.musicPlayBtn setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:(UIControlStateNormal)];
    }
    [self.musicPlayBtn addTarget:self action:@selector(musicPlayBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //下一首
    self.musicNextBtn.userInteractionEnabled = YES;
    [self.musicNextBtn addTarget:self action:@selector(musicNextBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
    //上一首
    self.musicLastBtn.userInteractionEnabled = YES;
    [self.musicLastBtn addTarget:self action:@selector(musicLastBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)musicPlayBtnAction{
    if ([LHAVPlayerManager shareInstant].avPlayer.rate == 0) {
        [[LHAVPlayerManager shareInstant] play];
        [self.musicPlayBtn setBackgroundImage:[UIImage imageNamed:@"暂停"] forState:(UIControlStateNormal)];
    }else if([LHAVPlayerManager shareInstant].avPlayer.rate == 1){
        [[LHAVPlayerManager shareInstant] pause];
        [self.musicPlayBtn setBackgroundImage:[UIImage imageNamed:@"播放"] forState:(UIControlStateNormal)];
    }
}

- (void)musicNextBtnAction{
    [LHRadioDetailViewController nextMusic];
}

- (void)musicLastBtnAction{
    [LHRadioDetailViewController lastMusic];
}

- (void)setUserViewWithName:(NSString *)name Img:(NSString *)imgStr{
    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectBtn.userInteractionEnabled = YES;
        self.nameBtn.userInteractionEnabled = NO;
        [self.collectBtn setTitle:@"个人收藏" forState:(UIControlStateNormal)];
        [self.nameBtn setTitle:name forState:(UIControlStateNormal)];
        [self.iconImgView sd_setImageWithURL:[NSURL URLWithString:imgStr]];
    });
}

- (void)nameBtnAction{
    [self showLoginVC];
    // 关闭抽屉
    [self hideLeftViewController];
}

- (void)collectBtnAction{
    
    if (![LHUserInfoManager shareManager].uid) {
        [self showAlertControllerWithStr:@"进入此页面,需要先登录哦!"];
        return;
    }
    //跳转到收藏页面
    UINavigationController *navc = [[UINavigationController alloc]initWithRootViewController:[[LHReadCollectController alloc] init]];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:navc animated:YES completion:nil];
    // 关闭抽屉
    [self hideLeftViewController];
}

- (void)showLoginVC{
    //跳转到登陆页面
    UINavigationController *navc = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"LoginAndRegist"];
    [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:navc animated:YES completion:nil];
}

- (void)showAlertControllerWithStr:(NSString *)str{
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:str preferredStyle:(UIAlertControllerStyleAlert)];
        [alertController addAction:[UIAlertAction actionWithTitle:@"前往登陆页面" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [[LHMenuViewController getMenuViewController] showLoginVC];
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]];
        [self presentViewController:alertController animated:YES completion:nil];
    });
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

+ (UIImageView *)rotate360DegreeWithImageView:(UIImageView *)imageView{
    CABasicAnimation *animation = [ CABasicAnimation
                                   animationWithKeyPath: @"transform" ];
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    
    //围绕Z轴旋转，垂直与屏幕
    animation.toValue = [ NSValue valueWithCATransform3D:
                         
                         CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0) ];
    animation.duration = 3;
    //旋转效果累计，先转180度，接着再旋转180度，从而实现360旋转
    animation.cumulative = YES;
    animation.repeatCount = NSIntegerMax;
    
    //在图片边缘添加一个像素的透明区域，去图片锯齿
    CGRect imageRrect = CGRectMake(0, 0,imageView.frame.size.width, imageView.frame.size.height);
    UIGraphicsBeginImageContext(imageRrect.size);
    [imageView.image drawInRect:CGRectMake(1,1,imageView.frame.size.width-2,imageView.frame.size.height-2)];
    imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [imageView.layer addAnimation:animation forKey:nil];
    return imageView;
}

@end
